package com.cloudwise.truelicensespringbootstarter.license.common;

import com.cloudwise.truelicensespringbootstarter.license.model.CustomKeyStoreParam;
import com.cloudwise.truelicensespringbootstarter.license.model.LicenseVerifyParam;
import de.schlichtherle.license.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;

/**
 * 校验license
 *
 * @author jeffery.li
 * @date 2022/6/8 11:22
 */
@Slf4j
public class LicenseVerify {

    /**
     * LicenseManager
     */
    private LicenseManager licenseManager;
    /**
     * 标识证书是否安装成功
     */
    private boolean installSuccess;

    private LicenseVerifyParam licenseVerifyParam;

    public LicenseVerify(LicenseVerifyParam licenseVerifyParam){
        this.licenseVerifyParam = licenseVerifyParam;
    }

    /**
     * 安装验证证书
     * @return
     */
    public LicenseContent installLicense() {
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);

        CipherParam cipherParam = new DefaultCipherParam(licenseVerifyParam.getStorePass());

        KeyStoreParam keyStoreParam = new CustomKeyStoreParam(LicenseVerify.class,
                licenseVerifyParam.getPublicKeysStorePath(),
                licenseVerifyParam.getPublicAlias(),
                licenseVerifyParam.getStorePass(), null);

        LicenseParam licenseParam = new DefaultLicenseParam(licenseVerifyParam.getSubject(), preferences, keyStoreParam, cipherParam);

        licenseManager = new CustomLicenseManager(licenseParam);
        try {

            if (installSuccess) {
                licenseManager.uninstall();
            }
            LicenseContent licenseContent = licenseManager.install(new File(licenseVerifyParam.getLicensePath()));
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            installSuccess = true;
            log.info("------------------------------- 证书安装成功 -------------------------------");
            log.info(MessageFormat.format("证书有效期：{0} - {1}", format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter())));

        } catch (Exception e) {
            installSuccess = false;
            log.error("------------------------------- 证书安装失败 -------------------------------");
            log.error("证书安装失败:" + e);
        }

        return null;
    }

    /**
     * 卸载证书，在bean从容器移除的时候自动调用
     */
    public void unInstallLicense() {
        if (installSuccess) {
            try {
                licenseManager.uninstall();
            } catch (Exception e) {
                // ignore
            }
        }
    }

    /**
     * 校验License证书
     */
    public boolean verify() {
        try {
            LicenseContent licenseContent = licenseManager.verify();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
